/**
 * Copyright 2007-2008. Chongqing First Information & Network Co., Ltd. All
 * rights reserved. <a>http://www.cqfirst.com.cn</a>
 */
package com.cq.bd.utils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.directwebremoting.WebContextFactory;

/**
 * 用户验证
 * 
 * @author huangmy
 * @date   2009-10-3
 */
public class AuthenticationHelper {

	/**
	 * The session key
	 */
	public static final String USER = AuthenticationHelper.class.getName() + ".USER";

	/**
	 * 设置当前session用户,用于系统登录
	 * 
	 * @param user
	 *            当前session用户
	 */
	public static void setUser(Object user) {
		HttpSession session = WebContextFactory.get().getSession(true);
		session.setAttribute(USER, user);
	}

	/**
	 * 获取当前session用户
	 * 
	 * @return 当前session用户
	 */
	public static Object getUser() {
		HttpSession session = WebContextFactory.get().getSession(true);
		return session.getAttribute(USER);
	}

	/**
	 * 清除当前session用户
	 */
	public static void removeUser() {
		HttpSession session = WebContextFactory.get().getSession(true);
		session.removeAttribute(USER);
	}

	/**
	 * 获取远程用户ipaddress
	 */
	public static String getIpAddress() {
		HttpServletRequest request = WebContextFactory.get().getHttpServletRequest();
		// return request.getRemoteAddr();

		String ip = request.getHeader("x-forwarded-for");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}
		return ip;
	}

	/**
	 * 获取sessionid
	 * 
	 * @return
	 */
	public static String getSessionId() {
		HttpSession session = WebContextFactory.get().getSession(true);
		return session.getId();
	}

	/**
	 * 退出登陆
	 */
	public static void loginOut() {
		HttpSession session = WebContextFactory.get().getSession();
		session.invalidate();
	}

}
